package com.example.lotterysystem.controller;
import com.example.lotterysystem.controller.result.GetActivityDetailResult.Prize;
import com.example.lotterysystem.controller.result.GetActivityDetailResult.User;
import java.util.ArrayList;

import com.example.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import com.example.lotterysystem.common.exception.ControllerException;
import com.example.lotterysystem.common.result.CommonResult;
import com.example.lotterysystem.common.utils.JacksonUtil;
import com.example.lotterysystem.controller.param.CreateActivityParam;
import com.example.lotterysystem.controller.param.PageParam;
import com.example.lotterysystem.controller.result.CreateActivityResult;
import com.example.lotterysystem.controller.result.FindActivityListResult;
import com.example.lotterysystem.controller.result.FindPrizeListResult;
import com.example.lotterysystem.controller.result.GetActivityDetailResult;
import com.example.lotterysystem.service.ActivityService;
import com.example.lotterysystem.service.dto.ActivityDTO;
import com.example.lotterysystem.service.dto.ActivityDetailDTO;
import com.example.lotterysystem.service.dto.CreateActivityDTO;
import com.example.lotterysystem.service.dto.PageListDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class ActivityController {
    @Autowired
    private ActivityService activityService;

    /**
     * 创建活动
     * @param param
     * @return
     */
    @RequestMapping("/activity/create")
    public CommonResult<CreateActivityResult> createActivity(
            @Validated @RequestBody CreateActivityParam param) {
        // 日志打印
        log.info("ActivityController createActivity 接收到参数 CreateActivityParam： {}",
                JacksonUtil.writeValueAsString(param));
        // 业务处理
        CreateActivityDTO createActivityDTO = activityService.createActivity(param);
        // 构造响应并返回
        return CommonResult.success(convertToCreateActivityResult(createActivityDTO));
    }

    /**
     * CreateActivityDTO -> CreateActivityResult
     * @param createActivityDTO
     * @return
     */
    private CreateActivityResult convertToCreateActivityResult(CreateActivityDTO createActivityDTO) {
        if(null == createActivityDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.ACTIVITY_CREATE_ERROR);
        }
        CreateActivityResult createActivityResult = new CreateActivityResult();
        createActivityResult.setActivityId(createActivityDTO.getActivityId());
        return createActivityResult;
    }

    /**
     * 查询活动列表
     * @param param
     * @return
     */
    @RequestMapping("/activity/find-list")
    public CommonResult<FindActivityListResult> findPageList(PageParam param) {
        // 日志打印
        log.info("findPageList 接收到参数 PageParam：{}", JacksonUtil.writeValueAsString(param));
        // 业务处理
       PageListDTO<ActivityDTO> activityDTOPageListDTO =  activityService.findActivityPageList(param);
        return CommonResult.success(convertToFindActivityListResult(activityDTOPageListDTO));
    }

    /**
     * PageListDTO<ActivityDTO> -> FindActivityListResult
     * @param activityDTOPageListDTO
     * @return
     */
    private FindActivityListResult convertToFindActivityListResult(PageListDTO<ActivityDTO> activityDTOPageListDTO) {
        if (null == activityDTOPageListDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.ACTIVITY_FIND_LIST_ERROR);
        }
        FindActivityListResult findActivityListResult = new FindActivityListResult();
        findActivityListResult.setTotal(activityDTOPageListDTO.getTotal());
        List<FindActivityListResult.ActivityInfo> activityInfoList = activityDTOPageListDTO.getRecords()
                .stream()
                .map(activityDTO -> {
                    FindActivityListResult.ActivityInfo activityInfo = new FindActivityListResult.ActivityInfo();
                    activityInfo.setActivityId(activityDTO.getActivityId());
                    activityInfo.setActivityName(activityDTO.getActivityName());
                    activityInfo.setDescription(activityDTO.getDescription());
                    activityInfo.setValid(activityDTO.valid());
                    return activityInfo;
                }).collect(Collectors.toList());
        findActivityListResult.setRecords(activityInfoList);
        return findActivityListResult;
    }

    /**
     * 查询活动信息
     * @param activityId
     * @return
     */
    @RequestMapping("/activity-detail/find")
    public CommonResult<GetActivityDetailResult> getActivityDetail(Long activityId) {
        // 日志打印
        log.info("getActivityDetail 接收到参数 activityId: {}", activityId);
        // 业务处理
        ActivityDetailDTO activityDetailDTO = activityService.getActivityDetail(activityId);
        // 构造响应
        return CommonResult.success(
                convertToGetActivityDetailResult(activityDetailDTO));
    }

    /**
     * 将 activityDetailDTO 转化为 GetActivityDetailResult 类型
     * @param activityDetailDTO
     * @return
     */
    private GetActivityDetailResult convertToGetActivityDetailResult(ActivityDetailDTO activityDetailDTO) {
        // 参数校验
        if (null == activityDetailDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.GET_ACTIVITY_INFO_ERROR);
        }
        log.info("convertToGetActivityDetailResult 接收到参数 activityDetailDTO: {}", JacksonUtil.writeValueAsString(activityDetailDTO));
        GetActivityDetailResult getActivityDetailResult = new GetActivityDetailResult();
        getActivityDetailResult.setActivityId(activityDetailDTO.getActivityId());
        getActivityDetailResult.setActivityName(activityDetailDTO.getActivityName());
        getActivityDetailResult.setDesc(activityDetailDTO.getDesc());
        getActivityDetailResult.setValid(activityDetailDTO.valid());
        // 抽奖顺序 一、二、三
        getActivityDetailResult.setPrizes(
                activityDetailDTO.getPrizeDTOList().stream()
                        .sorted(Comparator.comparingInt(prizeDTO -> prizeDTO.getTiers().getCode()))
                        .map(prizeDTO -> {
                            GetActivityDetailResult.Prize prize = new GetActivityDetailResult.Prize();
                            prize.setPrizeId(prizeDTO.getPrizeId());
                            prize.setName(prizeDTO.getPrizeName());
                            prize.setImageUrl(prizeDTO.getImageUrl());
                            prize.setPrice(prizeDTO.getPrize());
                            prize.setDescription(prizeDTO.getDescription());
                            prize.setPrizeTierName(prizeDTO.getTiers().name());
                            prize.setPrizeAmount(prizeDTO.getPrizeAmount());
                            prize.setValid(prizeDTO.valid());
                            return prize;
                        }).collect(Collectors.toList())
        );
        getActivityDetailResult.setUsers(
                activityDetailDTO.getUserDTOList().stream()
                        .map(userDTO -> {
                            GetActivityDetailResult.User user = new GetActivityDetailResult.User();
                            user.setUserId(userDTO.getUserId());
                            user.setUserName(userDTO.getUserName());
                            user.setValid(userDTO.valid());
                            return user;
                        }).collect(Collectors.toList())
        );
        return getActivityDetailResult;
    }
}
